package com.moon.tools.util;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @ClassName: Tools
 * @Description: 工具类
 * @Author: 郭正洋
 * @Date: 2022/11/14 14:22
 * @Vsersion: 1.0.0
 **/
public class Tools {

	/**
	 * 找出两个集合中不同的元素
	 *
	 * @param collmax
	 * @param collmin
	 * @return
	 */
	public static Collection getDifferListByMapPlus(Collection collmax, Collection collmin) {
		//使用LinkedList防止差异过大时,元素拷贝
		Collection csReturn = new LinkedList();
		Collection max = collmax;
		Collection min = collmin;
		long beginTime = System.currentTimeMillis();
		//先比较大小,这样会减少后续map的if判断次数
		if (collmax.size() < collmin.size()) {
			max = collmin;
			min = collmax;
		}
		//直接指定大小,防止再散列
		Map<Object, Integer> map = new HashMap<Object, Integer>(max.size());
		for (Object object : max) {
			map.put(object, 1);
		}
		for (Object object : min) {
			if (map.get(object) == null) {
				csReturn.add(object);
			} else {
				map.put(object, 2);
			}
		}
		for (Map.Entry<Object, Integer> entry : map.entrySet()) {
			if (entry.getValue() == 1) {
				csReturn.add(entry.getKey());
			}
		}
		long endTime = System.currentTimeMillis();
		System.out.println("集合A和集合B不同的元素："+csReturn);
		System.out.println("使用map方式遍历, 对比耗时: " + (endTime - beginTime)+"毫秒。");
		return csReturn;
	}


	/**
	 * 找出两个集合中相同的元素
	 *
	 * @param collmax
	 * @param collmin
	 * @return
	 */
	public static Collection getSameListByMap(Collection collmax, Collection collmin) {
		//使用LinkedList防止差异过大时,元素拷贝
		Collection csReturn = new LinkedList();
		Collection max = collmax;
		Collection min = collmin;
		//先比较大小,这样会减少后续map的if判断次数
		if (collmax.size() < collmin.size()) {
			max = collmin;
			min = collmax;
		}
		//直接指定大小,防止再散列
		Map<Object, Integer> map = new HashMap<Object, Integer>(max.size());
		for (Object object : max) {
			map.put(object, 1);
		}
		for (Object object : min) {
			if (map.get(object) != null) {
				csReturn.add(object);
			}
		}
		return csReturn;
	}

}
